package com.amado.course42Socket.tcp.chatSystem;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @author wangyulong
 * @version 1.5.0
 * @date 2020/3/7 19:03
 */
public class SocketUtil {
    public static Map<Long, Socket> map = new HashMap<>();
    public static void putSocket(Long id,Socket socket){
        map.put(id,socket);
    }
    public static Set<Long> getIdSet(){
        return map.keySet();
    }
    public static InputStream getInputStream(Long id) {
        Socket socket = getSocket(id);
        if (socket == null) return null;
        try {
            return socket.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    private static Socket getSocket(Long id) {
        Socket socket = map.get(id);
        if (socket == null) {
            System.out.printf("根据%s不能找到socket", String.valueOf(id));
            return null;
        }
        return socket;
    }

    public static OutputStream getOutputStream(Long id) {
        Socket socket = getSocket(id);
        if (socket == null) return null;
        try {
            return socket.getOutputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
